package com.abc.rule.aviator;

import com.googlecode.aviator.runtime.function.AbstractFunction;
import com.googlecode.aviator.runtime.function.FunctionUtils;
import com.googlecode.aviator.runtime.type.AviatorLong;
import com.googlecode.aviator.runtime.type.AviatorObject;
import com.googlecode.aviator.runtime.type.AviatorString;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Map;

public class DivideFunction extends AbstractFunction {

   @Override
   public AviatorObject call(Map<String, Object> env, AviatorObject arg1, AviatorObject arg2) {
      try{
         Object left = FunctionUtils.getJavaObject(arg1, env);
         Object right = FunctionUtils.getJavaObject(arg2, env);

         BigDecimal bi1 = doGetNumber(left);
         BigDecimal bi2 = doGetNumber(right);

         int index = bi2.compareTo(new BigDecimal(0));

         if (index == 0) {
            return new AviatorLong(0);
         }


         BigDecimal divide = bi1.divide(bi2, 2, RoundingMode.HALF_UP);

//         divide = divide.multiply(new BigDecimal(100));

//         Number number = divide.longValue();

         return new AviatorLong(divide.doubleValue());
      }catch (Exception e){

         return new AviatorLong(0);
      }

   }

   private BigDecimal doGetNumber(Object left) {
      BigDecimal total;
      if (left instanceof String) {
         total = new BigDecimal((String) left);
      }
      else if (left instanceof Integer) {
         total = new BigDecimal((Integer) left);
      }
      else if (left instanceof Long) {
         total = new BigDecimal((Long) left);
      }
      else if (left instanceof Double) {
         total = new BigDecimal((Double) left);
      }
      else {
         total = new BigDecimal(0);
      }
      return total;
   }

   @Override
   public String getName() {
      return "div";
   }
}
